package com.springboot.thymeleaf.springbootthymeleaf.moudle.sure;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.springboot.thymeleaf.springbootthymeleaf.config.SuErExpressConfig;
import com.springboot.thymeleaf.springbootthymeleaf.entity.SuErJsonExample;
import com.springboot.thymeleaf.springbootthymeleaf.entity.SuErRequestWaybillWay;
import com.springboot.thymeleaf.springbootthymeleaf.entity.returnVo.BookingReturnVo;
import com.springboot.thymeleaf.springbootthymeleaf.entity.vo.SuErResponseVo;
import com.springboot.thymeleaf.springbootthymeleaf.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import sun.net.www.http.HttpClient;


import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname ${小柯}
 * @Description TODO
 * @Date 2019/10/17 21:26
 * @Created by Administrator
 */
@Slf4j
public class SureUtils {




    public ResponseEntity<SuErResponseVo> getSuErRequest(SuErRequestWaybillWay suErRequestWaybillWay, SuErExpressConfig suErExpressConfig){
        SuErResponseVo suErResponseVo = new SuErResponseVo();
        BookingReturnVo bookingReturnVo = new BookingReturnVo();

        //srAppKey
        String srAppKey = suErExpressConfig.getSrAppKey();
        //秘钥srSecretKey
        String srSecretKey = suErExpressConfig.getSrSecretKey();
        //速尔token兑换地址
        String srTokenUrl = suErExpressConfig.getSrTokenUrl();

        //兑换token
        String token = getSrToken(srTokenUrl, srAppKey, srSecretKey);

        //客户Id
        String srClientId = suErExpressConfig.getSrClientId();
        //传送给对方的IP
        String serverIp = suErExpressConfig.getServerIp();
        //网点编号
        String srBranchNum = suErExpressConfig.getSrBranchNum();
        //客户编号 相当于月结卡号
        String srClineNum = suErExpressConfig.getSrClineNum();
        //取件员编号
        String srCourierNum = suErExpressConfig.getSrCourierNum();



        /**
         * 封装param 请求体
         */
        //List<SuErRequestWaybillWay> list = new ArrayList<>();

       // SuErRequestWaybillWay suErRequestWaybillWayToParams = new SuErRequestWaybillWay();

        SuErRequestWaybillWay requestWaybillWay = new SuErRequestWaybillWay();

        if(suErRequestWaybillWay != null){
            //公司名
            requestWaybillWay.setExpressCompany("SUR");
            //客户ID
            requestWaybillWay.setClientId(srClientId);
            //接口秘钥
            requestWaybillWay.setSecretKey(srSecretKey);
            //服务器IP
            requestWaybillWay.setServerIp(serverIp);
            //客户类型W网点
            requestWaybillWay.setClineType("W");
            //网点名称
            requestWaybillWay.setName("嘉立创总部");
            //网点编号
            requestWaybillWay.setBranchNum(srBranchNum);
            //客户编号
            requestWaybillWay.setClineNum(srClineNum);
            //取件员编号
            requestWaybillWay.setCourierNum(srCourierNum);
            //寄件人
            if(suErRequestWaybillWay.getSender() == null & "".equals(suErRequestWaybillWay.getSender())){
                suErResponseVo.setRemark("寄件人为空");
                suErResponseVo.setHeadingCode("500");
            }
            requestWaybillWay.setSender(suErRequestWaybillWay.getSender());
            //寄件人电话
            requestWaybillWay.setSenderPhone(suErRequestWaybillWay.getSenderPhone());
            //寄件人公司
            requestWaybillWay.setSenderCompany(suErRequestWaybillWay.getSenderCompany());
            //寄件人详细地址
            requestWaybillWay.setSenderAddr(suErRequestWaybillWay.getSenderAddr());
            //收件人
            requestWaybillWay.setReceiver("李四");
            //收件人电话
            requestWaybillWay.setReceiverPhone("12345678765");
            //收件人公司
            requestWaybillWay.setReceiverCompany("友和道通集团");
            //收件人省份
            requestWaybillWay.setReceiverProv("广东省");
            //收件人城市
            requestWaybillWay.setReceiverCity("深圳市");
            //收件人详细地址
            requestWaybillWay.setReceiverAddr("广东省深圳市福田区红荔西路现代苑");
            //物品名称
            requestWaybillWay.setGoodsCateogory("水果");
            //重量
            requestWaybillWay.setWeight("5");
            //货物件数
            requestWaybillWay.setCasesNum(5);
            //货物名称
            requestWaybillWay.setGoodsName("水果");
            //服务方式
            requestWaybillWay.setServiceMode("派送");
            //快件类型
            requestWaybillWay.setShipmentType("汽运");
            //付款方式
            requestWaybillWay.setPaymentMethod("寄付月结");
            //打印
            requestWaybillWay.setType("3");



        }else {
            suErResponseVo.setRemark("响应失败");
            suErResponseVo.setHeadingCode("500");
        }

      //  suErRequestWaybillWayToParams.add(requestWaybillWay);


        SuErJsonExample suErJsonExample = new SuErJsonExample();
        suErJsonExample.setAppKey(srAppKey);
        suErJsonExample.setToken(token);
        suErJsonExample.setParams(requestWaybillWay);
        String responseEntity = null;
        CloseableHttpClient httpClient = null;
        try {
            String body = JsonUtil.toJson(suErJsonExample);

            //suErExpressConfig
            String srApiUrl = suErExpressConfig.getSrApiUrl();
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(srApiUrl);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            StringEntity postingString = new StringEntity(body, "utf-8");
            httpPost.setEntity(postingString);

            HttpResponse response = httpClient.execute(httpPost);
            System.out.println(response.getStatusLine().getStatusCode() + "----");
            responseEntity = EntityUtils.toString(response.getEntity());


            System.out.println(responseEntity);
            SuErResponse suErResponse = JsonUtil.fromJson(responseEntity, SuErResponse.class);

            System.out.println(suErResponse);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {


            if(httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }


        return new ResponseEntity<SuErResponseVo>(suErResponseVo,HttpStatus.OK);
    }


    /**
     * 获取token
     * @param srTokenUrl
     * @param srAppKey
     * @param srSecretKey
     * @return
     */
    private static String getSrToken(String srTokenUrl, String srAppKey, String srSecretKey) {
        HttpURLConnection connection = null;
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(srTokenUrl).append("?").append("secretKey=").append(srSecretKey).append("&appKey=").append(srAppKey);
        URL url = null;
        String stringFromInputStream = null;
        try {
            url = new URL(stringBuffer.toString());
            connection = (HttpURLConnection)url.openConnection();
            //设置属性
            //设置请求方式
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setConnectTimeout(60 * 1000);
            connection.setReadTimeout(60 * 1000);
            //设置请求头
            connection.setRequestProperty("charsert", "UTF-8");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");//设置参数类型是json格式
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("logType", "base");


            connection.connect();

            //响应码
            int responseCode = connection.getResponseCode();
            System.out.println(responseCode);

            if(responseCode == 200){
                //得到响应流
                InputStream inputStream = connection.getInputStream();
                //将响应流转换成字符串
                stringFromInputStream = getStringFromInputStream(inputStream);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject jsonObject = JSONObject.parseObject(stringFromInputStream);

        String msg = jsonObject.getString("Msg");


        return msg;
    }


    /**
     * 通过字节输入流返回一个字符串信息
     */
    private static String getStringFromInputStream(InputStream is) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StringBuffer sb = new StringBuffer();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        is.close();
        // 把流中的数据转换成字符串, 采用的编码是: utf-8
        String status = baos.toString();
        baos.close();
        return status;
    }

}
